package com.tianpengcc.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tianpengcc.model.User;

public class IndeServlet extends HttpServlet {

	/**
	 * <p>Description:</p>
	 * <p>Compary</p>
	 * @author 田鹏
	 * @date 2017年10月24日下午8:39:40
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		if(session.getAttribute("user") != null){
			response.sendRedirect(request.getContextPath() + "/login.jsp");
			return ;
		}
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(int i = 0 ; i < cookies.length ; i++) {
				if("user".equals(cookies[i].getName())){
					String value = cookies[i].getValue();
					String[] userNameAndPassword = value.split("---");
					String userName = userNameAndPassword[0];
					String password = userNameAndPassword[1];
					System.out.println(cookies[i].getName() + "===" + cookies[i].getValue());
					request.setAttribute("user", new User(userName,password)) ;
				}
			}
		}
		request.getRequestDispatcher("/login.jsp").forward(request, response);
	}

}
